#include "udpServer.hpp"
#include "onlineUser.hpp"
#include <memory>
#include <fstream>
#include <unordered_map>
#include <signal.h>
using namespace std;
using namespace Server;



static void Usage(string proc)
{
    cout << "\nUsage:\n\t" << proc << " local_port\n\n";
}


/*业务三：服务器转发消息：向所有在线成员发送消息*/
OnlineUser onlineuser;
void routeMessage(int sockfd,string clientip,uint16_t clientport,string message)
{   
    if(message=="online") onlineuser.addUser(clientip,clientport);
    if(message=="offline") onlineuser.delUser(clientip,clientport);
    if(onlineuser.isOnline(clientip,clientport))
    {
        //消息的路由
        onlineuser.boardcastMessage(sockfd,clientip,clientport,message);
    }
    else
    {
        struct sockaddr_in client;
        bzero(&client,sizeof(client));
        client.sin_family=AF_INET;
        client.sin_addr.s_addr=inet_addr(clientip.c_str());
        client.sin_port=htons(clientport);

        //发送信息
        string response="请先上线再说话！！！，运行online";
        sendto(sockfd,response.c_str(),response.size(),0,(struct sockaddr *)&client,sizeof(client));

    }
}

int main(int argc,char* argv[])
{
    if(argc != 2)
    {
        Usage(argv[0]);
        exit(USAGE_ERR);
    }
    uint16_t port=atoi(argv[1]);

    std::unique_ptr<udpServer> usvr(new udpServer(routeMessage,port));
    
    usvr->initServer();
    usvr->start();

    return 0;
}